﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private CancellationTokenSource tokenSource = new CancellationTokenSource();
        public Form1()
        {
            InitializeComponent();
            ThreadPool.SetMaxThreads(1000, 1000);
        }

        private void downloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(GetImages);
        }

        private void cancelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tokenSource.Cancel();
        }

        private void GetImages()
        {
            //发送请求，获取输出流
            WebRequest webRequest = HttpWebRequest.Create("http://localhost:1398/TestThread/TestTask/Handler.ashx");
            Stream responseStream = webRequest.GetResponse().GetResponseStream();

            byte[] responseByte = new byte[81960];
            IAsyncResult result = responseStream.BeginRead(responseByte, 0, 81960, null, null);
            int responseLength = responseStream.EndRead(result);

            //获取图片数量
            int imageCount = BitConverter.ToInt32(responseByte, 0);

            //获取每副图片的长度
            int[] lengths = new int[imageCount];
            for (int n = 0; n < imageCount; n++)
            {
                int length = BitConverter.ToInt32(responseByte, (n + 1) * 4);
                lengths[n] = length;
            }
            try
            {
                //保存图片
                for (int n = 0; n < imageCount; n++)
                {
                    string path = string.Format("F:/Documents and Settings/Administrator/桌面/TemLib/测试/Solution1/WebApplication1/Images/pic{0}.jpg", n);
                    FileStream file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);

                    //计算字节偏移量
                    int offset = (imageCount + 1) * 4;
                    for (int a = 0; a < n; a++)
                        offset += lengths[a];

                    file.Write(responseByte, offset, lengths[n]);
                    file.Flush();

                    //模拟操作
                    Thread.Sleep(1000);

                    //检测CancellationToken变化
                    tokenSource.Token.ThrowIfCancellationRequested();
                }
            }
            catch (OperationCanceledException ex)
            {
                MessageBox.Show("Download cancel!");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
